package com.imy.luascript.retrofit.factory;



import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import androidx.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 在此写用途
 *
 * @author: Imy
 * @date: 2017-04-20
 */
public final class StringConverterFactory extends Converter.Factory {
  private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
  private static final Charset UTF_8 = Charset.forName("UTF-8");

  public static StringConverterFactory create() {
    return new StringConverterFactory();
  }

  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (type == String.class) {
      return new StringConverter();
    } else {
      //            throw new NullPointerException("type != String");
      return null;
    }
    //        return  null;
  }

  @Nullable
  @Override
  public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    return new StringRequestBodyConverter();
  }

  public static final class StringConverter implements Converter<ResponseBody, String> {

    public StringConverter() {
    }

    @Override
    public String convert(ResponseBody value) throws IOException {
      try {
        return value.string();
      } finally {
        value.close();
      }
    }
  }

  public static final class StringRequestBodyConverter implements Converter<String, RequestBody> {

    public StringRequestBodyConverter() {
    }

    @Override
    public RequestBody convert(String value) throws IOException {
      Buffer buffer = new Buffer();
      Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
      writer.write(value);
      writer.close();

      return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
    }
  }

}
